import * as turf from "@turf/turf";
//获取子任务区域经纬度（地图圈选父任务与省份的交集）
export const getSubTaskRegionIntersection = (taskRegion,provinceRegion) => {
    let resultRegion = "";
    console.log(taskRegion);
    //地图绘制区域
    let coordinates = [];//地图绘制区域经纬度
    if(taskRegion.indexOf("MULTIPOLYGON")==-1){
        let arr = taskRegion.split(";");
        if(arr!=null && arr.length>0){
            for(let j=0;j<arr.length;j++){
                let lonlatStr = arr[j].split(",");
                let lonlat = [];
                lonlat.push(Number(lonlatStr[0]));
                lonlat.push(Number(lonlatStr[1]));
                coordinates.push(lonlat);
            }
        }
    }
    console.log(coordinates);
    console.log("子任务选择省份区域:");
    console.log(provinceRegion);
    //子任务选择省份区域
    if(provinceRegion.indexOf("MULTIPOLYGON")!=-1){
        let all_coords_str = provinceRegion.split(";");
        let bool = false;
        for(let i=0;i<all_coords_str.length;i++){
            let coords_str = all_coords_str[i].split("MULTIPOLYGON (((")[1].split(")))")[0];
            let geometries = coords_str.split(")), ((");
            for (let k = 0;k < geometries.length;k++) {
                console.log("allPointsArr--多面--第"+k);
                let allPointsArr = [];
                let __coords = geometries[k].split("), (");
                for (let m = 0;m < __coords.length;m++) {
                    let _coords = __coords[m].split(", "), points = [];
                    for (let n = 0;n < _coords.length;n++) {
                        if(_coords[n]!=null && _coords[n]!=""){
                            let coord = _coords[n].split(" ");
                            let lon = Number(coord[0]), lat = Number(coord[1]);
                            let lonlat = [lon, lat];
                            points.push(lonlat);
                        }
                    }
                    allPointsArr.push(points);
                    //不对空洞的面进行相交处理
                    break;
                }
                console.log(allPointsArr);
                //获取相交的Polygon
                let intersection = getTurfIntersect(allPointsArr, [coordinates]);
                if(intersection!=null){
                    console.log("相交结果："+k);
                    let allPointCrossArray = intersection.geometry.coordinates;
                    console.log("子任务选择省份区域多面--第"+k);
                    console.log(allPointCrossArray);
                    if(allPointCrossArray!=null && allPointCrossArray.length>0){
                        for(let q=0;q<allPointCrossArray.length;q++){
                            let pointCrossArray = allPointCrossArray[q];//获取子数组
                            if(pointCrossArray!=null && pointCrossArray.length==1){
                                pointCrossArray = pointCrossArray[0];//获取子数组
                            }
                            if(pointCrossArray!=null && pointCrossArray.length>2){
                                if(resultRegion!=""){
                                    resultRegion += ";";
                                }
                                resultRegion += "MULTIPOLYGON (((";
                                for(let j=0;j<pointCrossArray.length;j++){
                                    let lonlat = pointCrossArray[j];
                                    if(j>0){
                                        resultRegion += ", ";
                                    }
                                    resultRegion += lonlat[0] + " "+ lonlat[1];
                                }
                                resultRegion += ")))";
                                bool = true;
                                console.log(resultRegion);
                            }
                        }
                    }
                }
                if(bool){
                    //break;
                }
            }
            if(bool){
                //break;
            }
        }
    }
    console.log("获取子任务省份相交区域经纬度：resultRegion");
    console.log(resultRegion);
    return resultRegion;
}

//获取重合Polygon
export const getTurfIntersect = (coordinate1, coordinate2) => {
    /*let poly1 = {
        geometry: {
            coordinates: [coordinate1],
            type: "Polygon"
        },
        properties: {},
        type: "Feature"
    }

    let poly2 = {
        geometry: {
            coordinates: [coordinate2],
            type: "Polygon"
        },
        properties: {},
        type: "Feature"
    }*/

    /*let poly1 = turf.polygon([[
            [-122.801742, 45.48565],
            [-122.801742, 45.60491],
            [-122.584762, 45.60491],
            [-122.584762, 45.48565],
            [-122.801742, 45.48565]
        ]]);

    let poly2 = turf.polygon([[
        [-122.520217, 45.535693],
        [-122.64038, 45.553967],
        [-122.720031, 45.526554],
        [-122.669906, 45.507309],
        [-122.723464, 45.446643],
        [-122.532577, 45.408574],
        [-122.487258, 45.477466],
        [-122.520217, 45.535693]
    ]]);*/
    console.log("coordinate1:");
    console.log(coordinate1);
    console.log("coordinate2:");
    console.log(coordinate2);
    let poly1 = turf.polygon(coordinate1);
    let poly2 = turf.polygon(coordinate2);
    //面相交
    let intersection = turf.intersect(poly2, poly1);

    return intersection
}

//获取中心点
export const getMapLngLatCenter = (array) => {
    let center = {}
    let arr1 = JSON.parse(JSON.stringify(array));
    let arr2 = JSON.parse(JSON.stringify(array));
    arr1.sort(function (x, y) {
        return y.lat - x.lat
    })
    center.lat = (arr1[0].lat+arr1[arr1.length-1].lat)/2
    arr2.sort(function (x, y) {
        return y.lng - x.lng
    })
    center.lng  = (arr2[0].lng+arr2[arr2.length-1].lng)/2
    return [center.lng, center.lat]
}

//计算两点间距离
export const getPointsDistance = (p1, p2) => {
    //p1,p2数组形式 [经度,纬度]
    let from = turf.point(p1);
    let to = turf.point(p2);
    let options = {units: 'kilometers'};//单位km
    //计算两点间距离
    let result = turf.distance(from, to, options);
    //转换单位 米
    result = result * 1000;

    return result;
}

//计算区域面积
export const getAreaByPolygonCoordinates = (coordinates) => {
    //p1,p2数组形式 [经度,纬度]
    /*let polygon = turf.polygon([[
        [108.09876, 37.200787],
        [106.398901, 33.648651],
        [114.972103, 33.340483],
        [113.715685, 37.845557],
        [108.09876, 37.200787]
    ]]);*/
    let polygon = turf.polygon([coordinates]);
    let area = turf.area(polygon);//平方米

    return area;
}

//点到多段线的最短距离
export const getPointDistanceByLineString = (point,coordinates) => {
    /*point = [108, 37];
    coordinates = [
        [108.09876, 37.200787],
        [106.398901, 33.648651],
        [114.972103, 33.340483],
        [113.715685, 37.845557]
    ];*/
    let pt = turf.point(point);
    let line = turf.lineString(coordinates);
    //点到多段线的最短距离
    let distance = turf.pointToLineDistance(pt, line, {units: 'kilometers'});//单位km
    //console.log("点到多段线的最短距离"+distance);

    return distance;
}

//计算点到多段线的最短距离的点经纬度
export const getLonLatByPointLine = (point,coordinates) => {
    /*point = [108, 37];
    coordinates = [
        [108.09876, 37.200787],
        [106.398901, 33.648651],
        [114.972103, 33.340483],
        [113.715685, 37.845557]
    ];*/
    let pt = turf.point(point);
    let line = turf.lineString(coordinates);
    //计算点到多段线的最短距离的点
    let snapped = turf.nearestPointOnLine(line, pt, {units: 'kilometers'});//单位km
    //console.log(snapped);
    let lonlat = snapped.geometry.coordinates;

    return lonlat;
}

//计算两点间的角度
export const getAngleByPointsLonLat = (lonlat1,lonlat2) => {
    //lonlat1 = [109.104262, 37.831315];
    //lonlat2 = [102.865569, 34.089941];
    let point1 = turf.point(lonlat1);
    let point2 = turf.point(lonlat2);
    //计算两点间的角度，从正北算起的角度(0度)
    let angle = turf.bearing(point1, point2);
    console.log(angle);

    return angle;
}

//计算线段与线段的交点
export const getLineIntersect = (coordinates1,coordinates2) => {
    coordinates1 = [[126, -11], [129, -21]];
    coordinates2 = [[123, -18], [131, -14]];
    let line1 = turf.lineString(coordinates1);
    let line2 = turf.lineString(coordinates2);
    let intersects = turf.lineIntersect(line1, line2);

    return intersects;
}

//计算线段与面的交点
export const getLinePolygonIntersect = (coordinates1,coordinates2) => {
    coordinates1 = [[126, -11], [129, -21]];
    coordinates2 = [[
        [-122.801742, 45.48565],
        [-122.801742, 45.60491],
        [-122.584762, 45.60491],
        [-122.584762, 45.48565],
        [-122.801742, 45.48565]
    ]];
    let line = turf.lineString(coordinates1);
    let polygon = turf.polygon(coordinates2);
    let intersects = turf.lineIntersect(line, polygon);

    return intersects;
}

//判断第二个几何图形是否完全包含在第一个几何图形内（点是否在面内部）
export const getPolygonContainsPointBoolean = (coordinates1,coordinates2) => {
    /*coordinates1 = [[
        [123, 45],
        [122, 45],
        [122, 46],
        [123, 46],
        [123, 45]
    ]];
    coordinates2 = [123, 45];*/
    console.log("判断第二个几何图形是否完全包含在第一个几何图形内（点是否在面内部）");
    console.log(coordinates1);
    console.log(coordinates2);
    let polygon = turf.polygon(coordinates1);
    let point = turf.point(coordinates2);
    //判断第二个几何图形是否完全包含在第一个几何图形内
    let bool = turf.booleanContains(polygon, point);
    console.log(bool);

    return bool;
}

//判断第二个几何图形是否完全包含在第一个几何图形内（线是否在面内部）
export const getPolygonContainsLineBoolean = (coordinates1,coordinates2) => {
    coordinates1 = [[
        [123, 45],
        [122, 45],
        [122, 46],
        [123, 46],
        [123, 45]
    ]];
    coordinates2 = [[122.8, 45.49], [122.8, 45.5]];
    console.log("判断第二个几何图形是否完全包含在第一个几何图形内（线是否在面内部）");
    console.log(coordinates1);
    console.log(coordinates2);
    let polygon = turf.polygon(coordinates1);
    let line = turf.lineString(coordinates2);
    //判断第二个几何图形是否完全包含在第一个几何图形内
    let bool = turf.booleanContains(polygon, line);
    console.log(bool);

    return bool;
}

//根据点截取多线段
export const getSliceLineByPoints = (coordinates,startLonLat,stopLonLat) => {
    /*coordinates =  [
        [-77.031669, 38.878605],
        [-77.029609, 38.881946],
        [-77.020339, 38.884084],
        [-77.025661, 38.885821],
        [-77.021884, 38.889563],
        [-77.019824, 38.892368]
    ];
    startLonLat = [-77.029609, 38.881946];
    stopLonLat = [-77.021884, 38.889563];*/
    let line = turf.lineString(coordinates);
    let startPoint = turf.point(startLonLat);
    let stopPoint = turf.point(stopLonLat);
    //获取一条线、起点和终点，并返回这些点之间的线段。起止点不需要正好落在直线上
    let sliced = turf.lineSlice(startPoint, stopPoint, line);
}

//根据距离截取线段
export const getSliceLineByDistance = (coordinates,startDistance,stopDistance) => {
    //coordinates = [[7, 45], [9, 45], [14, 40], [14, 41]];
    startDistance = 1;
    stopDistance = 1;
    console.log(coordinates);
    console.log(startDistance);
    let line = turf.lineString(coordinates);
    //取一条线，沿该线到起始点的指定距离，以及沿该线到终止点的指定距离，并返回这些点之间的该线的分段
    let sliced = turf.lineSliceAlong(line, startDistance, stopDistance, {units: 'kilometers'});
    //获取线的经纬度数组
    let slicedLineCoordinates = sliced.geometry.coordinates;

    return slicedLineCoordinates;
}

//分割多线段
export const getChunkLineByDistance = (coordinates,distance) => {
    /*coordinates = [[-95, 40], [-93, 45], [-85, 50]];
    distance = 15;*/
    let line = turf.lineString(coordinates);
    //将一个LineString分割成指定长度的块。如果LineString比分隔段长度短，则返回原始LineString
    let chunk = turf.lineChunk(line, distance, {units: 'kilometers'});

    return chunk;
}

//获取面内的线段（相交）
export const getLineLonLatByPolygon = (coordinates1,coordinates2) => {
    coordinates1 = [[-122.801742, 45.48565], [-122.584762, 45.60491]];
    coordinates2 = [[
        [-122.801742, 45.48565],
        [-122.801742, 45.60491],
        [-122.584762, 45.60491],
        [-122.584762, 45.48565],
        [-122.801742, 45.48565]
    ]];
    let line = turf.lineString(coordinates1);
    let polygon = turf.polygon(coordinates2);

    let overlapping = turf.lineOverlap(line, polygon);
    //获取线的经纬度数组
    //let overlappingArray = overlapping.geometry.coordinates;
    console.log("获取线的经纬度数组");
    console.log(overlapping);
    if(overlapping.features.length>0){
        console.log(overlapping.features[0].geometry.coordinates);
    }
}

//判断点是否在面内部
export const booleanPointInPolygon = (coordinates1,coordinates2) => {
    var pt = turf.point([-81, 41]);
    var poly = turf.polygon([[
        [-81, 41],
        [-81, 47],
        [-72, 47],
        [-72, 41],
        [-81, 41]
    ]]);

    let bool = turf.booleanPointInPolygon(pt, poly);

    return bool;
}

//根据经纬度计算线的长度（米）
export const getLineLengthByCoords = (coordinates) => {
    console.log("根据经纬度计算线的长度（米）");
    console.log(coordinates);
    //coordinates = [[115, -32], [131, -22], [143, -25], [150, -34]];
    let line = turf.lineString(coordinates);
    let length = turf.length(line, {units: 'kilometers'});
    length = length * 1000;

    return length;
}

//根据经纬度范围和格网距离生成正方形网格
export const createSquareGrid = (bbox,cellSide) => {
    //bbox = [106.47828704100004, 29.531042141000057 ,106.58861877300006, 29.574831737000068];
    //cellSide = 30;
    let options = {units: 'kilometers'};
    let squareGrid = turf.squareGrid(bbox, cellSide, options);
    console.log("根据经纬度范围和格网距离生成正方形网格");
    console.log(squareGrid);

    return squareGrid;
}

//根据经纬度范围和格网距离生成点网格
export const createPointGrid = (bbox,cellSide) => {
    //bbox = [106.47828704100004, 29.531042141000057 ,106.58861877300006, 29.574831737000068];
    //cellSide = 30;
    let options = {units: 'kilometers'};
    let pointGrid = turf.pointGrid(bbox, cellSide, options);
    console.log("根据经纬度范围和格网距离生成点网格");
    console.log(pointGrid);

    return pointGrid;
}

//根据距离获取度数
export const getDegreeByDistance = (distance) => {
    //turf.lengthToDegrees(6671704.814011974, 'kilometers'); // 60
    console.log("根据距离获取度数");
    let degree = turf.lengthToDegrees(distance, 'kilometers');
    console.log(degree);

    return degree;
}



